package com.easyn.P2PCamLive.Deluxe;

import java.util.List;

import com.MyApplication;
import com.easyn.P2PCam264.AddDeviceActivity;
import com.easyn.CamLinePro.DeviceListActivity;
import com.easyn.CamLinePro.R;
import com.hichip.HiSmartWifiSet;

import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class AddDeviceSelectSet extends Activity {
	
	private EditText editPwd;
	private TextView editSSID;
	
	private byte mAuthMode;
	private WifiManager mWifiManager;
	private String ip;
	private String mConnectedSsid;
	private String mAuthString;	
	
	private AlertDialog dialog;
	private View dialogView;
	private ProgressBar pb;
	private TextView tv_left;
	private TextView tv_right;
	
	private boolean isChecked = false;
	private Handler aphandler = new Handler();
	private int iprocess = 1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_add_device_select_set);
		editPwd = (EditText)findViewById(R.id.editPwd);
		editSSID = (TextView)findViewById(R.id.editSSID);
		// 屏幕常亮
				PowerManager powerManager = (PowerManager) this
						.getSystemService(this.POWER_SERVICE);
				MyApplication.sWakeLock = powerManager.newWakeLock(
						PowerManager.FULL_WAKE_LOCK, "My Lock");
		wifiSetting();
		
		dialog = new AlertDialog.Builder(this).create();
		
		dialogView = LinearLayout.inflate(this, R.layout.activity_add_device_process, null);
				
		pb = (ProgressBar) dialogView.findViewById(R.id.progressBar);
		tv_left = (TextView) dialogView.findViewById(R.id.txt_left);
		tv_right = (TextView) dialogView.findViewById(R.id.txt_right);
		editSSID.setFocusable(true);
	}
	
//	private Runnable runable = new Runnable(){
//		@Override
//		public void run(){ 
//			iprocess += 2;
//			pb.setProgress(iprocess);
//			tv_left.setText(iprocess/10+"%");
//			tv_right.setText(iprocess/10+"/100");
//			if(iprocess >=1000)
//			{
//				Exit();
//				AddDeviceActivity.gAutoSearch = true;
//				DeviceListActivity.gAddOld = true;
//				finish();
//				return;
//			}
//			aphandler.postDelayed(runable,100);
//		}
//	};
	private Runnable runable = new Runnable() {
		@Override
		public void run() {
			iprocess += 2;
			pb.setProgress(iprocess);
			tv_left.setText(iprocess / 10 + "%");
			tv_right.setText(iprocess / 10 + "/100");
			if (iprocess >= 1000) {
				Exit();
				// AddDeviceActivity.gAutoSearch = true;
				// DeviceListActivity.gAddOld = true;
				DeviceListActivity.nPageIndex = 1;
				Intent Intent = new Intent();
				setResult(99, Intent);
				finish();
				return;
			}
			aphandler.postDelayed(runable, 100);// for test ++
			// aphandler.postDelayed(runable,1);//for test --

		}
	};
	
	private void showdlg(){
		if (dialog != null && !dialog.isShowing())
		{
			dialog.show();
			dialog.setContentView(dialogView);
			dialog.setCanceledOnTouchOutside(false);
			dialog.setCancelable(false);
			Window dialogWindow = dialog.getWindow();
	        WindowManager.LayoutParams lp = dialogWindow.getAttributes();	        
	        dialogWindow.setGravity(Gravity.CENTER);
	        //lp.y = 100;
	        dialogWindow.setAttributes(lp);
	        aphandler.postDelayed(runable,100);	        
		}
	}
	
	private void Exit(){
		HiSmartWifiSet.HiStopSmartConnection();
		if(dialog.isShowing())
			dialog.dismiss();
	}	
	
	private void wifiSetting() {
		mWifiManager = (WifiManager) getSystemService (Context.WIFI_SERVICE);
		if(mWifiManager.isWifiEnabled())
		{
        	WifiInfo WifiInfo = mWifiManager.getConnectionInfo();
        	
        	//MulticastLock multicastLock = WifiInfo.createMulticastLock("multicast.test");
        	//multicastLock.acquire();
        	
            int ipAddress = WifiInfo.getIpAddress(); //获取本地IP地址
            ip =(ipAddress & 0xFF ) + "." + ((ipAddress >> 8 ) & 0xFF) + "." + ((ipAddress >> 16 ) & 0xFF)+ "." +0xFF;
       	
        	mConnectedSsid = WifiInfo.getSSID();
			int iLen = mConnectedSsid.length();
			if (mConnectedSsid.startsWith("\"") && mConnectedSsid.endsWith("\""))
			{
				mConnectedSsid = mConnectedSsid.substring(1, iLen - 1);
			}
			
			
	//		mConnectedSsid = mConnectedSsid.replace('\"', ' ');
	//		mConnectedSsid = mConnectedSsid.trim();
			editSSID.setText(mConnectedSsid);
		//	Log.d(TAG, "SSID = " + mConnectedSsid);
		//	Log.d(TAG, "onCread = " + mConnectedSsid);
			
			List<ScanResult> ScanResultlist = mWifiManager.getScanResults();
			for (int i = 0, len = ScanResultlist.size(); i < len; i++) 
			{
				ScanResult AccessPoint = ScanResultlist.get(i);			
				if (AccessPoint.SSID.equals(mConnectedSsid))
				{		
					//	Log.d(TAG, "WIFI info = " + AccessPoint.capabilities);
					boolean WpaPsk = AccessPoint.capabilities.contains("WPA-PSK");
		        	boolean Wpa2Psk = AccessPoint.capabilities.contains("WPA2-PSK");
					boolean Wpa = AccessPoint.capabilities.contains("WPA-EAP");
		        	boolean Wpa2 = AccessPoint.capabilities.contains("WPA2-EAP");
					boolean Tkip = AccessPoint.capabilities.contains("TKIP");
		        	boolean AES = AccessPoint.capabilities.contains("CCMP");
										
					if (AccessPoint.capabilities.contains("WEP"))
					{
						mAuthString = "OPEN-WEP";
						mAuthMode = HiSmartWifiSet.AuthModeWEPOPEN;
						break;
					}
					
					
					/**********
					 * 
					 * WPAPSK WPA2PSK Auto 
					 * 
					 **********/
					if (WpaPsk && Wpa2Psk && AES && Tkip)
					{
						mAuthString = "WPA-PSK WPA2-PSK TKIP AES";
						mAuthMode = HiSmartWifiSet.AuthModeWPA1PSKWPA2PSKTKIPAES;
						break;
					}
					
					
					if (WpaPsk && Wpa2Psk && Tkip)
					{
						mAuthString = "WPA-PSK WPA2-PSK TKIP";
						mAuthMode = HiSmartWifiSet.AuthModeWPA1PSKWPA2PSKTKIP;
						break;
					}
					
					
					if (WpaPsk && Wpa2Psk && AES)
					{
						mAuthString = "WPA-PSK WPA2-PSK AES";
						mAuthMode = HiSmartWifiSet.AuthModeWPA1PSKWPA2PSKAES;
						break;
					}	
					
					
					/**********
					 * 
					 * WPA2PSK 
					 * 
					 **********/	
					if (Wpa2Psk && AES && Tkip)
					{
						mAuthString = "WPA2-PSK TKIP";
						mAuthMode = HiSmartWifiSet.AuthModeWPA2PSKTKIPAES;
						break;
					}	
					
					if (Wpa2Psk && Tkip)
					{
						mAuthString = "WPA2-PSK TKIP";
						mAuthMode = HiSmartWifiSet.AuthModeWPA2PSKTKIP;
						break;
					}
					
					if (Wpa2Psk && AES)
					{
						mAuthString = "WPA2-PSK AES";
						mAuthMode = HiSmartWifiSet.AuthModeWPA2PSKAES;
						break;
					}	
					

					/**********
					 * 
					 * WPAPSK 
					 * 
					 **********/
					if (WpaPsk && AES && Tkip)
					{
						mAuthString = "WPA-PSK TKIP";
						mAuthMode = HiSmartWifiSet.AuthModeWPAPSKTKIPAES;
						break;
					}	
					
					if (WpaPsk && Tkip)
					{
						mAuthString = "WPA-PSK TKIP";
						mAuthMode = HiSmartWifiSet.AuthModeWPAPSKTKIP;
						break;
					}
					
					if (WpaPsk && AES)
					{
						mAuthString = "WPA-PSK AES";
						mAuthMode = HiSmartWifiSet.AuthModeWPAPSKAES;
						break;
					}	
					


					/**********
					 * 
					 * WPA-EAP  WPA-EAP2 AUTO 
					 * 
					 **********/
					if (Wpa && Wpa2)
					{
						mAuthString = "WPA-EAP WPA2-EAP";
						mAuthMode = HiSmartWifiSet.AuthModeWPA1EAPWPA2EAP;
						break;
					}
					
					/**********
					 * 
					 * WPA-EAP2  
					 * 
					 **********/
					if (Wpa2)
					{
						mAuthString = "WPA2-EAP";
						mAuthMode = HiSmartWifiSet.AuthModeWPA2EAP;
						break;
					}
					
					/**********
					 * 
					 * WPA-EAP 
					 * 
					 **********/					
					if (Wpa)
					{
						mAuthString = "WPA-EAP";
						mAuthMode = HiSmartWifiSet.AuthModeWPAEAP;
						break;
					}									
					/**********
					 * 
					 * Open
					 * 
					 **********/	
					mAuthString = "OPEN";
					mAuthMode = HiSmartWifiSet.AuthModeOpen;					
				}
			}
			Log.d("camera", "Auth Mode  = " + mAuthString);
		}
	}	
	
	public void onSet(View v){
		String Password = editPwd.getText().toString();
		if(Password.length()==0){
			Toast.makeText(this,  getText(R.string.add_pass_empty).toString(), Toast.LENGTH_SHORT).show();
			return;
		}
		
		Log.i("tag", "Start Connection ssid:"+mConnectedSsid+ " Password:"+Password + " mode:"+ mAuthString);
		int iret = HiSmartWifiSet.HiStartSmartConnection(mConnectedSsid, Password, mAuthMode);
		Log.i("tag", String.valueOf(iret));
		
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if(iret != 0){
			//Toast.makeText(this,  getText(R.string.adddeviceselect_wifierror).toString(), Toast.LENGTH_SHORT).show();
			//Toast.makeText(this,  "设置失败", Toast.LENGTH_SHORT).show();
			Exit();
		}
		else{
			//Toast.makeText(this,  "设置成功", Toast.LENGTH_SHORT).show();
			showdlg();
			
//			DeviceListActivity.gAddOld = true;
//			finish();						
			
//			Intent intent = new Intent();
//			Bundle extras = new Bundle();
//			AddDeviceActivity.gAutoSearch = true;
//			extras.putInt("addMode", AddDeviceActivity.ADD_DEVICE_FROM_WIRELESS);
//			intent.putExtras(extras);
//			intent.setClass(AddDeviceSelectSet.this, AddDeviceActivity.class);
//			startActivityForResult(intent,DeviceListActivity.REQUEST_CODE_CAMERA_ADD);
		}
	}
	
	public void onck(View view) {
		if (!isChecked) {
			editPwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);     
		}else {
			editPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);    
		}
		isChecked = !isChecked;
	}
	@Override
	protected void onResume() {
		super.onResume();
		MyApplication.sWakeLock.acquire();
	}

}
